<template>
  <div class="user_add_or_update">
    <el-dialog
      :visible.sync="visible"
      :title="!dataForm.id ? $t('add') : $t('update')"
      destroy-on-close
      append-to-body
      @closed="onClosed"
      custom-class="user-management-dialog"
      width="920px"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        class="user-management-form"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmitHandle()"
        v-loading="loading"
      >
        <el-tooltip
          class="item"
          :open-delay="1000"
          effect="dark"
          :content="$t('user.tooltipcontent')"
          placement="top"
        >
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item :label="$t('user.username')" prop="username">
                <el-input
                  v-model="dataForm.username"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.username')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                class="email"
                prop="email"
                :label="$t('user.email')"
              >
                <el-input
                  v-model="dataForm.email"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.email')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('user.firstName')" prop="firstName">
                <el-input
                  v-model="dataForm.firstName"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.firstName')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('user.lastName')" prop="lastName">
                <el-input
                  v-model="dataForm.lastName"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.lastName')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('user.displayName')" prop="realName">
                <el-input
                  v-model="dataForm.realName"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.displayName')"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="$hasPermission('sys:user:password')">
              <el-form-item label="Password" prop="password">
                <el-input
                  v-model="dataForm.password"
                  :show-password="dataForm.id"
                  :disabled="true"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('user.mobile')" prop="mobile">
                <el-input
                  v-model="dataForm.mobile"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.mobile')"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                :label="$t('user.businessPhones')"
                prop="businessPhones"
              >
                <el-input
                  v-model="dataForm.businessPhones"
                  :disabled="dataForm.id"
                  :placeholder="$t('user.businessPhones')"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tooltip>
        <el-divider content-position="left">JOB INFORMATION</el-divider>
        <el-row :gutter="24" style="margin-top: 22px;">
          <el-col :span="12">
            <el-form-item :label="$t('user.managerName')">
              <el-select
                v-model="dataForm.managerId"
                :disabled="dataForm.id"
                style="width: 100%"
                filterable
                clearable
                default-first-option
                :placeholder="$t('user.managerName')"
              >
                <el-option
                  v-for="user in managerList"
                  :key="user.id"
                  :label="user.username + ' (' + user.email + ')'"
                  :value="user.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('user.deptName')" v-if="!isMe">
              <ren-dept-tree
                v-model="dataForm.deptId"
                :placeholder="$t('dept.title')"
                :dept-name.sync="dataForm.deptName"
              ></ren-dept-tree>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="User Type"
                          prop="regSource">
              <el-select v-model="dataForm.regSource"
                         style="width:100%"
                         placeholder="Select">
                <el-option v-for="(item, index) in userTypeOptions"
                           :key="index"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-divider content-position="left">ACCOUNT INFORMATION</el-divider>
        <el-row :gutter="24" style="margin-top: 22px;">
          <el-col :span="24">
            <el-form-item prop="roleIdList" :label="$t('user.roleIdList')">
              <el-select
                v-model="roleIds"
                multiple
                collapse-tags
                style="width: 100%"
                :disabled="isMe"
                :placeholder="$t('user.roleIdList')"
              >
                <el-option
                  v-for="(role, index) in fullRoleList"
                  :key="index"
                  :label="role.name"
                  :value="role.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <ZCardSwitch
                label="Status"
                :active-value="1"
                :inactive-value="0"
                :disabled="isMe"
                v-model="dataForm.status"
                @change="statusChange"
                desc="After a user's account is suspended, that user will not be able to log in."
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <ZCardSwitch
                label="Message"
                :disabled="disabledUser"
                v-model="dataForm.teamsMessageSwitch"
                desc="After closing the message, the user's teams will no longer receive messages from MSPbots.ai."
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('user.homeChannel')">
              <div style="position:relative;z-index: 99999;">
                <el-input v-model="homeChannelinput"
                          @input="channelInput"
                          @focus="channelFocus"
                          @blur="channelBlur"
                          ref="channel-input"
                          clearable
                          :placeholder="$t('user.homeChannel')"></el-input>
                <div class="custom-collapse-css card-css scroll-css"
                     v-if="setChannelStatus"
                     @click="clickChannelCard">
              <el-collapse accordion
                               v-model="activeNames">
                    <el-collapse-item v-for="(value, key) in teamsChannelList"
                                      :key="key"
                                      :name="key">
                      <template slot="title">
                        {{ key }}
                      </template>
                      <template v-for="(it, j) in value">
                        <div :key="j">
                          <el-radio
                            v-model="dataForm.homeChannel"
                            :label="it.channelId"
                            >{{ it.displayName }}</el-radio
                          >
                        </div>
                      </template>
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="$hasPermission('sys:report:homepage')"
              :label="$t('custom.component.viewComponent.homepage')"
            >
              <el-select
                v-model="dataForm.homePage"
                style="width: 100%"
                filterable
                clearable
                :placeholder="$t('custom.component.viewComponent.homepage')"
              >
                <el-option
                  v-for="item in dashboardList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left">
          THIRD-PARTY PLATFORM MAPPING
        </el-divider>

        <el-row :gutter="24" style="margin-top: 22px;">
          <el-col :span="12">
            <el-form-item
              v-if="connectorSetting['CW']"
              prop="cwUserMapping"
              :label="$t('user.cwUserMapping')"
            >
              <el-select
                v-model="dataForm.cwUid"
                style="width: 100%"
                filterable
                :disabled="disabledUser"
                default-first-option
                :placeholder="$t('user.cwUserMapping')"
              >
                <el-option
                  v-for="item in mappingLists.cwUserList"
                  :key="item.cwUid"
                  :label="item.email"
                  :value="item.cwUid"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="connectorSetting['TEAMS']"
              prop="teamsUserMapping"
              :label="$t('user.teamsUserMapping')"
            >
              <el-select
                v-model="dataForm.teamsUserId"
                style="width: 100%"
                filterable
                :disabled="disabledUser"
                default-first-option
                :placeholder="$t('user.teamsUserMapping')"
              >
                <el-option
                  v-for="item in mappingLists.teamsUserList"
                  :key="item.teamsUserId"
                  :label="item.teamsMail"
                  :value="item.teamsUserId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="connectorSetting['TSHEET']"
              prop="sheetsUserMaapping"
              :label="$t('user.sheetsUserMaapping')"
            >
              <el-select
                v-model="dataForm.sheetUserId"
                style="width: 100%"
                filterable
                :disabled="disabledUser"
                default-first-option
                :placeholder="$t('user.sheetsUserMaapping')"
              >
                <el-option
                  v-for="item in mappingLists.sheetsUserList"
                  :key="item.sheetUserId"
                  :label="item.email"
                  :value="item.sheetUserId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="connectorSetting['TD']"
              prop="timeDoctorUserMapping"
              :label="$t('user.timeDoctorUserMapping')"
            >
              <el-select
                v-model="dataForm.timedoctorUser"
                style="width: 100%"
                filterable
                :disabled="disabledUser"
                default-first-option
                :placeholder="$t('user.timeDoctorUserMapping')"
              >
                <el-option
                  v-for="item in mappingLists.timedoctorUserList"
                  :key="item.userId"
                  :label="item.email"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="connectorSetting['AUTOTASK']"
              prop="autotaskUserMapping"
              :label="$t('user.autotaskUserMapping')"
            >
              <el-select
                v-model="dataForm.autotaskUser"
                style="width: 100%"
                filterable
                :disabled="disabledUser"
                default-first-option
                :placeholder="$t('user.autotaskUserMapping')"
              >
                <el-option
                  v-for="item in mappingLists.autotaskUserList"
                  :key="item.userId"
                  :label="item.email"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="connectorSetting['SYNCROMSP']"
              prop="syncroUserMapping"
              :label="$t('user.syncroUserMapping')"
            >
              <el-select
                v-model="dataForm.syncroUser"
                style="width: 100%"
                filterable
                :disabled="disabledUser"
                default-first-option
                :placeholder="$t('user.syncroUserMapping')"
              >
                <el-option
                  v-for="item in mappingLists.syncroUserList"
                  :key="item.otherId"
                  :label="item.email"
                  :value="item.otherId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="connectorSetting['KASEYABMS']" prop="kaseyabmsUserMapping"
                          :label="$t('user.kaseyabmsUserMapping')">
              <el-select v-model="dataForm.kaseyabmsUser"
                         style="width:100%;"
                         filterable
                         :disabled="disabledUser"
                         default-first-option
                         :placeholder="$t('user.kaseyabmsUserMapping')">
                <el-option v-for="item in mappingLists.kaseyaBmsUserList"
                           :key="item.otherId"
                           :label="item.email"
                           :value="item.otherId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="connectorSetting['JIRA']" prop="jiraUserMapping"
                          :label="$t('user.jiraUserMapping')">
              <el-select v-model="dataForm.jiraUser"
                         style="width:100%;"
                         filterable
                         :disabled="disabledUser"
                         default-first-option
                         :placeholder="$t('user.jiraUserMapping')">
                <el-option v-for="item in mappingLists.jiraUserList"
                           :key="item.key"
                           :label="item.email"
                           :value="item.key">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="connectorSetting['HALO']" prop="haloUserMapping"
                          :label="$t('user.haloUserMapping')">
              <el-select v-model="dataForm.haloUser"
                         style="width:100%;"
                         filterable
                         :disabled="disabledUser"
                         default-first-option
                         :placeholder="$t('user.haloUserMapping')">
                <el-option v-for="item in mappingLists.haloUserList"
                           :key="item.otherId"
                           :label="item.email"
                           :value="item.otherId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="connectorSetting['SLACK']" prop="slackUserMapping"
                          :label="$t('user.slackUserMapping')">
              <el-select v-model="dataForm.slackUser"
                         style="width:100%;"
                         filterable
                         :disabled="disabledUser"
                         default-first-option
                         :placeholder="$t('user.slackUserMapping')">
                <el-option v-for="item in mappingLists.slackUserList"
                           :key="item.otherId"
                           :label="item.realName"
                           :value="item.otherId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template slot="footer">
        <el-button @click="visible = false" size="small">{{
          $t('cancel')
        }}</el-button>
        <el-button
          type="primary"
          size="small"
          @click="dataFormSubmitHandle()"
          >{{ $t('confirm') }}</el-button
        >
      </template>
    </el-dialog>
    <el-dialog
      :title="$t('custom.apps.warning')"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span style="font-size: 14px; color: #404040; line-height: 22px">{{
        $t('user.warning')
      }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          size="mini"
          @click=";(dialogVisible = false), (dataForm.status = 1)"
          >{{ $t('cancel') }}</el-button
        >
        <el-button type="primary" size="mini" @click="dialogVisible = false">{{
          $t('user.disable')
        }}</el-button>
        <el-button
          type="primary"
          size="mini"
          :disabled="!$hasPermission('sys:user:update')"
          @click="
            ;(dialogVisible = false),
              (dataForm.status = 1),
              (dataForm.teamsMessageSwitch = false)
          "
          >{{ $t('user.Turnusersmessageswitch') }}</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import ZCardSwitch from '@/components/storybook/z-card-switch'
import qs from 'qs'
import { USER_TYPE_OPTIONS } from '@/components/storybook/b-user-actions/index.schema'
import config from '@/utils/config'
import { isEmail } from '@/utils/validate'
export default {
  components: {
    ZCardSwitch
  },
  props: {
    connectorSetting: {
      type: Object,
      default: () => {
        return {}
      }
    },
    userBillableVisible: {},
    userBillableType: {},
    userIsWhite: Function,
    isAlaCarte: {
      type: Boolean
    },
    payUserRequest: Boolean
  },
  data () {
    return {
      cloneForm: {},
      userTypeOptions: Object.freeze(USER_TYPE_OPTIONS),
      dialogVisible: false,
      homeChannelinput: '',
      activeNames: [],
      visible: false,
      roleList: [],
      managerList: [],
      roleIdListDefault: [],
      loading: false,
      dataForm: {
        id: undefined,
        username: '',
        firstName: '',
        lastName: '',
        deptId: '',
        deptName: '',
        businessPhones: '',
        password: '0*HzMe@1972Z',
        confirmPassword: '0*HzMe@1972Z',
        realName: '',
        gender: 0,
        email: '',
        mobile: '',
        roleIdList: [],
        status: 1,
        managerId: '',
        cwUid: '',
        teamsUserId: '',
        sheetUserId: '',
        timedoctorUser: '',
        autotaskUser: '',
        syncroUser: '',
        kaseyabmsUser: '',
        jiraUser: '',
        haloUser: '',
        slackUser: '',
        teamsMessageSwitch: true,
        homeChannel: '',
        homePage: '',
        regSource: '1'
      },
      mappingLists: {
        cwUserList: [],
        teamsUserList: [],
        sheetsUserList: [],
        timedoctorUserList: [],
        autotaskUserList: [],
        syncroUserList: [],
        kaseyaBmsUserList: [],
        jiraUserList: [],
        haloUserList: [],
        slackUserList: []
      },
      tempMappingList: [
        {
          userId: null,
          userType: '1',
          mappingUserId: null,
          tenantCode: this.$store.state.user.tenantCode,
          id: null
        },
        {
          userId: null,
          userType: '2',
          mappingUserId: null,
          tenantCode: this.$store.state.user.tenantCode,
          id: null
        },
        {
          userId: null,
          userType: '3',
          mappingUserId: null,
          tenantCode: this.$store.state.user.tenantCode,
          id: null
        },
        {
          userId: null,
          userType: '4',
          mappingUserId: null,
          tenantCode: this.$store.state.user.tenantCode,
          id: null
        }
      ],
      disabledUser: false,
      setChannelStatus: false,
      tempCardHas: false,
      teamsChannelList: [],
      assignRoleList: [],
      dashboardList: [],
      payUserParams: {}
    }
  },
  computed: {
    dataRule () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      var validateConfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          return callback(new Error(this.$t('validate.required')))
        }
        if (this.dataForm.password !== value) {
          return callback(new Error(this.$t('user.validate.confirmPassword')))
        }
        callback()
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          return callback(new Error(this.$t('user.validate.email')))
        }
        callback()
      };
      return {
        username: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        deptName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        regSource: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        firstName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        lastName: [
          {
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        realName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        email: [
           { validator: validateEmail, trigger: 'blur' }
        ],
        mobile: [
          // { validator: validateMobile, trigger: 'blur' }
        ],
        cwUid: [],
        teamsUserId: [],
        sheetUserId: [],
        timedoctorUser: [],
        autotaskUser: []
      }
    },
    isMe (val) {
      if (this.dataForm.id === this.$store.state.user.id) {
        return true
      }
      if (!this.$hasPermission('sys:user:assignrole')) {
        return true
      }
    },
    dataFormHomeChannel () {
      return this.dataForm.homeChannel
    },
    fullRoleList () {
      let roleList = this.roleList
      let assignRoleList = this.assignRoleList
      let roleTemp = []
      let assignTemp = []
      let temp = []
      roleList.forEach(ii => {
        roleTemp.push({
          roleId: ii.roleId,
          name: ii.name
        })
      })
      assignRoleList.forEach(it => {
        assignTemp.push({
          roleId: it.assignId,
          name: ''
        })
      })
      if (assignTemp.length > 0) {
        temp = this._.intersectionBy(roleTemp, assignTemp, 'roleId')
      } else {
        temp = roleTemp
      }
      return temp
    },
    roleIds: {
      set (val) {
        if (this._.intersection(val, config.freeUserRole).length > 0 || val.includes(config.nextTicketRoleOnlyId)) {
          this.dataForm.roleIdList = [val[val.length - 1]]
        } else {
          let index = val.findIndex(i => i.includes(config.freeUserRole))
          if (index > -1) {
            val.splice(index, 1)
          }
          this.dataForm.roleIdList = val || []
        }
      },
      get () {
        return this.dataForm.roleIdList
      }
    }
  },

  watch: {
    visible (val) {
      if (!val) {
        this.dataForm.teamsUserId = null
        this.dataForm.id = null
        this.dataForm.cwUid = null
        this.dataForm.sheetUserId = null
        this.dataForm.timedoctorUser = null
        this.dataForm.autotaskUser = null
        this.dataForm.homeChannel = null
        this.dataForm.homePage = null
      }
    },
    dataFormHomeChannel (val) {
      this.homeChannelinput = this.homeChannelLabel()
      this.teamsChannelList = this.dataForm.teamsChannelList
    }
  },
  methods: {
    onClosed () {
      this.$emit('event:cancel')
    },
    getReportList () {
      const params = {
        queryType: 'REFRESHCACHE',
        layoutType: 'report_layout',
        showAllIntegration: false,
        resourceType:0
      }
      return this.$interface.reports
        .getReportCardList(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dashboardList = res.data
        })
        .catch(() => {})
    },
    statusChange (val) {
      if (!val) {
        if (
          !this.dataForm.isGuestUser &&
          (this.dataForm.cwUserName || this.dataForm.autoTaskUserName)
        ) {
          this.dialogVisible = true
        }
      }
    },
    homeChannelLabel () {
      try {
        let tempList = []
        for (const key in this.dataForm.teamsChannelList) {
          tempList = [...tempList, ...this.dataForm.teamsChannelList[key]]
        }
        return (
          tempList.find(e => e.channelId === this.dataForm.homeChannel)
            .groupName +
          '/' +
          tempList.find(e => e.channelId === this.dataForm.homeChannel)
            .displayName
        )
      } catch (err) {
        return null
      }
    },
    channelFocus () {
      this.setChannelStatus = true
    },
    channelInput: debounce(function (str) {
      this.activeNames = []
      let channelList = {}
      if (str) {
        for (const key in this.dataForm.teamsChannelList) {
          if (Object.hasOwnProperty.call(this.dataForm.teamsChannelList, key)) {
            const element = this.dataForm.teamsChannelList[key]
            if (key.toLowerCase().indexOf(str.toLowerCase()) !== -1) {
              channelList[key] = element
            }
            element.forEach(ele => {
              if (
                ele.displayName.toLowerCase().indexOf(str.toLowerCase()) !== -1
              ) {
                if (channelList.hasOwnProperty(key)) {
                  channelList[key].push(ele)
                } else {
                  this.activeNames.push(key)
                  channelList[key] = []
                  channelList[key].push(ele)
                }
              }
            })
          }
        }
        this.teamsChannelList = channelList
      } else {
        this.homeChannelinput = ''
        this.dataForm.homeChannel = null
        this.activeNames = []
        this.teamsChannelList = this.dataForm.teamsChannelList
      }
    }, 800),
    channelBlur () {
      setTimeout(() => {
        if (!this.tempCardHas) {
          this.setChannelStatus = false
        }
      }, 300)
    },
    clickChannelCard (e) {
      if (e.target.tagName === 'DIV') {
        this.tempCardHas = true
        this.$refs['channel-input'].focus()
        setTimeout(() => {
          this.tempCardHas = false
        }, 300)
      }
    },
    init () {
      this.getReportList()
      this.visible = true
      this.dataForm.deptId = ''
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.roleIdListDefault = []
        this.getRoleList()
        this.getMappingList()
        this.getAssignRoleList()
        this.getManager()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    getRoleList () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      return this.$interface.system
        .getClientRoleListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
        })
        .catch(() => {})
    },
    getAssignRoleList () {
      let temp = []
      let roleList = this.$store.state.user.roleList
      roleList.forEach(it => {
        temp.push(it.id)
      })
      var params = qs.stringify(
        {
          roleId: temp
        },
        { arrayFormat: 'repeat' }
      )
      this.$interface.um.getAssignRoleList(params).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.assignRoleList = res.data
      })
    },
    getInfo () {
      this.loading = true
      this.$interface.system
        .getUserInfoWithIdApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = Object.assign({}, this.dataForm, res.data, {
            roleIdList: []
          })
          this.teamsChannelList = this.dataForm.teamsChannelList
          for (var i = 0; i < res.data.roleIdList.length; i++) {
            if (
              this.fullRoleList.filter(
                item => item.roleId === res.data.roleIdList[i]
              )[0]
            ) {
              this.dataForm.roleIdList.push(res.data.roleIdList[i])
              continue
            }
            this.roleIdListDefault.push(res.data.roleIdList[i])
          }
          this.cloneForm = this._.cloneDeep(this.dataForm)
          this.disabledUser = false
          if (res.data.status === 0) {
            this.disabledUser = true
          }
          let tempList = res.data.mappingList
          tempList &&
            tempList.length &&
            tempList.length > 0 &&
            (this.tempMappingList = tempList)
          tempList.find(e => e.userType === '1')
            ? (this.dataForm.teamsUserId = tempList.find(
              e => e.userType === '1'
            ).mappingUserId)
            : (this.dataForm.teamsUserId = null)
          tempList.find(e => e.userType === '2')
            ? (this.dataForm.cwUid = tempList.find(
              e => e.userType === '2'
            ).mappingUserId)
            : (this.dataForm.cwUid = null)
          tempList.find(e => e.userType === '3')
            ? (this.dataForm.sheetUserId = tempList.find(
              e => e.userType === '3'
            ).mappingUserId)
            : (this.dataForm.sheetUserId = null)
          tempList.find(e => e.userType === '4')
            ? (this.dataForm.timedoctorUser = tempList.find(
              e => e.userType === '4'
            ).mappingUserId)
            : (this.dataForm.timedoctorUser = null)
          tempList.find(e => e.userType === '5')
            ? (this.dataForm.autotaskUser = tempList.find(
              e => e.userType === '5'
            ).mappingUserId)
            : (this.dataForm.autotaskUser = null)
          tempList.find(e => e.userType === '6')
            ? (this.dataForm.syncroUser = tempList.find(
              e => e.userType === '6'
            ).mappingUserId)
            : (this.dataForm.syncroUser = null)
          tempList.find(e => e.userType === '7')
            ? (this.dataForm.kaseyabmsUser = tempList.find(
              e => e.userType === '7'
            ).mappingUserId)
            : (this.dataForm.kaseyabmsUser = null)
          tempList.find(e => e.userType === '8')
            ? (this.dataForm.jiraUser = tempList.find(
              e => e.userType === '8'
            ).mappingUserId)
            : (this.dataForm.jiraUser = null)
          tempList.find(e => e.userType === '9')
            ? (this.dataForm.haloUser = tempList.find(
              e => e.userType === '9'
            ).mappingUserId)
            : (this.dataForm.haloUser = null)
          tempList.find(e => e.userType === '10')
            ? (this.dataForm.slackUser = tempList.find(
              e => e.userType === '10'
            ).mappingUserId)
            : (this.dataForm.slackUser = null)
          // autotaskUser
          this.loading = false
        })
        .catch(() => {})
    },
    getManager () {
      this.$interface.system
        .getUserManagerListApi({
          id: this.dataForm.id,
          tenantCode: this.dataForm.tenantCode
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.managerList = res.data
        })
        .catch(() => {})
    },
    getMappingList () {
      const params = {}
      this.dataForm.id && (params.userId = this.dataForm.id)
      this.$interface.taskManager
        .getUserMappingListApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.mappingLists = res.data
        })
        .catch(() => {})
    },
    arrayUpdateWay (arr, nexArr) {
      nexArr &&
        nexArr.length &&
        nexArr.map(e => {
          arr.push(e)
        })
    },
    buildMapping () {
      let mappingList = []
      let arr = ['1', '2', '3', '4', '5', '6', '7','8','9','10']
      arr.forEach(userType => {
        let mappingUserId = null
        switch (userType) {
          case '1':
            mappingUserId = this.dataForm.teamsUserId
            break
          case '2':
            mappingUserId = this.dataForm.cwUid
            break
          case '3':
            mappingUserId = this.dataForm.sheetUserId
            break
          case '4':
            mappingUserId = this.dataForm.timedoctorUser
            break
          case '5':
            mappingUserId = this.dataForm.autotaskUser
            break
          case '6':
            mappingUserId = this.dataForm.syncroUser
            break
          case '7':
            mappingUserId = this.dataForm.kaseyabmsUser
            break
          case '8':
            mappingUserId = this.dataForm.jiraUser
            break
          case '9':
            mappingUserId = this.dataForm.haloUser
            break
          case '10':
            mappingUserId = this.dataForm.slackUser
            break
          default:
        }
        if (mappingUserId) {
          let mapping = this.tempMappingList.find(
            item => item.userType === userType
          )
          if (mapping != null) {
            mapping.mappingUserId = mappingUserId
          } else {
            mapping = {
              userId: this.dataForm.id,
              userType: userType,
              mappingUserId: mappingUserId,
              tenantCode: this.dataForm.tenantCode
            }
          }
          mappingList.push(mapping)
        }
      })
      return mappingList
    },
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs['dataForm'].validate(async valid => {
          if (!valid) {
            return false
          }
          let params = {
            status: null
          }
           // not charge
           this.cloneForm.roleIdList = this.cloneForm.roleIdList || []
          const isWhite = this.userIsWhite(this.dataForm)
          const dashboardOnly = this._.intersection(config.freeUserRole, this.cloneForm.roleIdList).length > 0 && this._.intersection(config.freeUserRole, this.dataForm.roleIdList).length > 0

          const disableToDashboard = !this.cloneForm.status && this._.intersection(config.freeUserRole, this.dataForm.roleIdList).length > 0
          const addUserDisable = Boolean(!this.dataForm.id) && !this.dataForm.status
          const notChange = this.cloneForm.status === this.dataForm.status && this.cloneForm.roleIdList.sort().toString() === this.dataForm.roleIdList.sort().toString()
          const statusDisable = this.cloneForm.status === this.dataForm.status && !this.dataForm.status

          const notChargeRole = !(this._.intersection(config.freeUserRole, this.cloneForm.roleIdList).length > 0)
              && !(this._.intersection(config.freeUserRole, this.dataForm.roleIdList).length > 0) && this.cloneForm.status === this.dataForm.status

          if (isWhite || dashboardOnly || disableToDashboard || addUserDisable || notChange || statusDisable ||  notChargeRole || this.isAlaCarte) {
            this.dataFormSubmitResponse()
          } else {
            const addUser = Boolean(!this.dataForm.id) && this.dataForm.status && !(this._.intersection(config.freeUserRole, this.dataForm.roleIdList).length > 0)
            // charge
            const roleChange = this.cloneForm.roleIdList.sort().toString() !== this.dataForm.roleIdList.sort().toString()
            const statusChange = this.cloneForm.status !== this.dataForm.status
            if ((addUser || roleChange || statusChange) && this.dataForm.status && !(this._.intersection(config.freeUserRole, this.dataForm.roleIdList).length > 0)) {
              params.status = 1
            } else {
              params.status = 2
            }

            params['userIds'] = [addUser ? '12345' : this.dataForm.id]


            const { queryNumberByUsers } = this.$interface.pay
            const { data } = await queryNumberByUsers(params)
            const { dtoList } = data.data

            this.payUserParams = {
              type: params.status,
              bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null
            }
            if (data.data.dtoList && data.data.dtoList.length > 0) {
              this.$emit('update:dtoList', dtoList)
              this.$emit('update:userBillableVisible', true)
              this.$emit('update:userBillableType', String(params.status))
              this.$emit('update:userBillable', '4')
            } else {
              this.dataFormSubmitResponse()
              if (params.status === 1) {
                if (!this.dataForm.id) {
                  this.payUserParams.count = 1
                } else {
                  this.payUserParams.userIdList = [this.dataForm.id]
                }
                const { payUser } = this.$interface.pay
                payUser(this.payUserParams).then()
              }
            }
          }
          const userChangeToOther = this.cloneForm.roleIdList.sort().toString() !== this.dataForm.roleIdList.sort().toString() && (this._.intersection(config.freeUserRole, this.dataForm.roleIdList).length > 0)
          if (this.dataForm.id && (userChangeToOther || !this.dataForm.status)) {
            const { alaCarteUpdate } = this.$interface.pay
            alaCarteUpdate({
              attendance: !!(this.dataForm.roleIdList.includes(config.attendanceOnlyId) && this.dataForm.status),
              userIds: [this.dataForm.id]
            })
          }
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
    dataFormSubmitResponse (no) {
      let mappingListData = this.buildMapping()
      const params = {
        ...this.dataForm,
        roleIdList: [...this.dataForm.roleIdList, ...this.roleIdListDefault],
        mappingList: mappingListData
      }
      delete params.teamsChannelList
      delete params.roleList
      delete params.tenantList
      delete params.idList
      const changeSysUser = () => {
        if (!this.dataForm.id) {
          this.payUserParams.count = 1
          return this.$interface.system.postSysUser(params)
        } else {
          this.payUserParams.userIdList = [this.dataForm.id]
          return this.$interface.system.putSysUser(params)
        }
      }
      this.loading=true
      changeSysUser()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            this.loading=false
            return this.$message.error(res.msg)
          }
          if (this.payUserRequest && !no) {
            const { payUser } = this.$interface.pay
            payUser(this.payUserParams).finally(() => {
              this.$emit('update:payUserRequest', false)
            })
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.loading=false
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        })
        .catch(() => {this.loading=false})
    }
  }
}
</script>

<style lang="scss">
.user-management-dialog {
  .el-divider__text.is-left {
    left: 0;
    padding-left: 0;
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
    font-weight: 600;
  }
  .el-dialog__header {
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
    }
  }
  .el-dialog__footer {
    border-top: 1px solid rgba(0, 0, 0, 0.08);
    padding: 23px 21px;
  }
  .el-form-item {
    margin-bottom: 16px;

    .el-form-item__label {
      font-size: 14px;
      color: #404040;
      font-weight: 600;
      line-height: 14px;
      height: 22px;
      &::before {
        display: none;
      }
    }

    .el-form-item__content {
      .el-input__inner {
        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px white inset !important;
        }
      }
    }
  }
}
.user-management-form {
  .card-css {
    position: absolute;
    width: 100%;
    max-height: 250px;
    padding: 12px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
    color: #303133;
    -webkit-transition: 0.3s;
    transition: 0.3s;
    margin-bottom: 30px;
  }
  .el-form-item__label {
    padding: 0 13px 0 0;
  }
  ::v-deep .el-dialog__body {
    overflow: inherit;
  }
}
</style>
